package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.entity.Category;
import com.itheima.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * ClassName: CategoryController
 * Package: com.itheima.controller
 * Description:
 *
 * @Author: @Albert
 * @Version: 1.0
 */
@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryController {
    @Autowired
    private CategoryService service;

    @PostMapping
    public R<String> save(@RequestBody Category category){
        log.info("前端传过来的参数{}",category.toString());
        service.save(category);
        return R.success("新增分类成功");
    }

    @GetMapping("/page")
    public R<Page> getList(int page,int pageSize){
        Page pageInfo = new Page(page,pageSize);
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper();
        //wrapper.like(!StringUtils.isEmpty(name), Employee::getName,name);
        //添加排序条件
        wrapper.orderByAsc(Category::getUpdateTime);
        service.page(pageInfo,wrapper);
        return R.success(pageInfo);
    }

    @DeleteMapping()
    public R<String> delete(Long id){
        log.info("前端发送删除分类消息,分类ID为{}",id);
        service.remove(id);
        return R.success("删除成功");

    }
    @PutMapping
    public R<String> update(@RequestBody Category category){
        service.updateById(category);
        return R.success("修改成功");
    }

    /**
     * 查询分类数据
     * @param category
     * @return
     */
    @GetMapping("/list")
    public R<List<Category>> list(Category category){
        log.info("执行菜品功能的分类查询列表");
        //条件构造器
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        //添加条件
        wrapper.eq(category.getType() !=null,Category::getType,category.getType());
        //添加排序条件
        wrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = service.list(wrapper);
        return R.success(list);
    }

}
